//create by lwy 2017年2月7日15:43:08
var newPage=0;//最新商家分页
var hotPage=0;//热门商家分页
var newNum;
var city = '郑州市';
var ifClose=true;

$(function(){
	//setCityItem('ifClose','true');
	if(getItem('ifClose')=='false'){
		$('.guide').hide();
	}else{
		$('.guide').show();
	}
})
$('#close').click(function(){
	$('.guide').hide();
	setTimeCookie('ifClose','false');
})
//点击下载
$('#download').click(function(){
	goDownload();
})

// 去下载
function goDownload() {
	var u = navigator.userAgent, app = navigator.appVersion;
	var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;
	var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
	// 是安卓浏览器
	if (isAndroid) {
		// 是微信内部webView
		if (is_weixn()) {
			alert("请点击右上角按钮，使用浏览器打开助利商城，浏览器打开后再点“点击下载”按钮即可下载安装。");
		}else{
			window.location.href = 'http://www.ddmzl.com/zl.apk'; // 跳安卓端下载地址
		}
	}
	// 是iOS浏览器
	if (isIOS) {
		window.location.href = 'https://itunes.apple.com/cn/app/id1263406469?mt=8'; // 跳AppStore下载地址
	}



}

// 是微信浏览器
function is_weixn(){
	var ua = navigator.userAgent.toLowerCase();
	if(ua.match(/MicroMessenger/i)=="micromessenger") {
		return true;
	} else {
		return false;
	}
}




//跳转至搜索商品页面
$(function(){
	$('.index-input').click(function(){
		window.location.href='search.html';
	})
})

//最新商家
function doNewShop(){
	newPage++;
	$.ajax({
		url:'/shopC/queryNewShop.json',
		dataType:'json',
		type:'post',
		data:{
			page:newPage,
			start:20,
			city:city,
			xianId:xianId,
		},
		success:function(data){
			if(data.code==1){
				var data = data.datas;
				for(var i=0;i<data.length;i++){
					if(data.length==0){
						$('<div class="kong"><img src="../img/kong.png" alt="暂无数据"></div>').appendTo($('.newShop'))
					}
					var isNew = data[i].isNewShop;
					if(data[i].isNewShop==0){
						isNew='';
					}else{
						isNew='<div class="newShop-right-sign"><img src="../img/newShop-sign.png" alt="新店"></div>'
					}
					$('<div class="newShop-item mui-clearfix" id="'+data[i].ID+'">'+
						'<div class="newshop-img"><img src="'+data[i].MinImg+'" alt="加载中" class="newShop-logo"></div>'+
						'<div class="newShop-box">'+
						'<p class="newShop-title">'+data[i].ShopName+'</p>'+
						'<p class="newShop-star"><img src="../img/star.png" alt=""></p>'+
						'<p class="newShop-sign">优质好店</p>'+
						'<p class="newShop-line"></p>'+
						'<p class="newShop-user"><img src="../img/newShop-user.png" alt="店主">'+data[i].RealName+'</p>'+
						'<p class="newShop-phone"><img src="../img/newShop-phone.png" alt="电话">'+data[i].Phone+'</p>'+
						'<p class="newShop-location"><img src="../img/newShop-location.png" alt="地址">'+data[i].ShopAddress+'</p>'+
						'</div>'+ isNew+
						'</div>').appendTo($('.newShop'))
				}
				newNum=data.length;
			}
		}
	})
	return newNum;
}

//热门商家
function doHotShop(){
	hotPage++;
	$.ajax({
		url:'/shopC/getPopShop.json',
		dataType:'json',
		type:'post',
		data:{
			page:hotPage,
			more:0,
			city:city,
			xianId:xianId,
		},
		beforeSend:function(){
			$('<div class="loading" style="text-align: center;width: 100%;height: 380px;line-height: 200px;">加载中...</div>').appendTo($('#swiper-wrapper'))
		},
		success:function(data){
			if(data.code==1){
				var data = data.datas;
				$('#hotShop').empty();
				if(data.length==0){
					$('<div class="kong" style="margin: 78px auto 20px auto;text-align: center;color: #b8b8b8;">当前城市暂无数据</div>').appendTo($('#hotShop'));
					mui('#refreshContainer').pullRefresh().disablePullupToRefresh();
				}
				for(var i=0;i<data.length;i++){
					$('<div class="swiper-slide hotWidth" id="'+data[i].ID+'">'+
						'<div class="hot-box">'+
						'<div class="hot-img"><img src="'+data[i].MinImg+'"/></div><p>'+data[i].ShopName+'</p><img class="star" src="../img/star.png">'+
						'</div></div>').appendTo($('#hotShop'))
				}
				$(document).ready(function(){
					$(".hot-img img").on("load",function(){
						var m = $('.hotWidth').width();
						$('.hot-box').css('height',m+'px');
					});
				});
				//swiper两个半
				var swiper = new Swiper('.swiper-container', {
					slidesPerView: 2.8,
					centeredSlides: false,
					paginationClickable: true,
					spaceBetween: 10,
					observer: true,//修改swiper自己或子元素时，自动初始化swiper
					observeParents: true//修改swiper的父元素时，自动初始化swiper
				});
			}
		}
	})
}

//点击跳转商家详情页
mui('body').on('tap','.hotWidth,.newShop-item',function(){
	var shopId = $(this).attr('id');
	window.location.href="shop_v2.html?shopId="+shopId;
})
//跳转登录页
var login = document.getElementById("login");
login.addEventListener("tap",function () {
	window.location.href="login.html";
});

//跳转至更多商家
var more = document.getElementById('more');
more.addEventListener('tap',function(){
	window.location.href="shop_list.html?hot=hot&page=1";
})

//跳转商家列表
mui('body').on('tap','.sort-box a',function(){
	var categoryId = $(this).attr('id');
	var categoryName = $(this).attr('name');
	window.location.href=encodeURI(encodeURI("shop_list.html?categoryId="+categoryId+"&page=1"+"&categoryName="+categoryName));
})

//跳转至地址
var present = document.getElementById('present');
present.addEventListener('tap',function(){
	window.location.href="rankCity.html";
})

//跳转至消息
var news = document.getElementById('news');
news.addEventListener('tap',function(){
	window.location.href="personal-news.html";
})

//上拉加载下拉刷新
mui.init({
	pullRefresh : {
		container:"#refreshContainer",//待刷新区域标识，querySelector能定位的css选择器均可，比如：id、.class等
		down: {
			contentdown : "下拉可以刷新",//可选，在下拉可刷新状态时，下拉刷新控件上显示的标题内容
			contentover : "释放立即刷新",//可选，在释放可刷新状态时，下拉刷新控件上显示的标题内容
			contentrefresh : "正在刷新...",//可选，正在刷新状态时，下拉刷新控件上显示的标题内容
			callback: function () {
				window.location.reload();
				mui('#refreshContainer').pullRefresh().endPulldownToRefresh();
			}
		},
		up : {
			contentrefresh : "正在加载...",//可选，正在加载状态时，上拉加载控件上显示的标题内容
			contentnomore:'我是有底线的',//可选，请求完毕若没有更多数据时显示的提醒内容；
			callback :function(){
				setTimeout(function () {
					var numResult = doNewShop();
					if (numResult < 20) {
						mui('#refreshContainer').pullRefresh().endPullupToRefresh(true);
					} else {
						mui('#refreshContainer').pullRefresh().endPullupToRefresh(false);
					}
				}, 1000);
			} //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
		}
	}
});

////mui下拉去掉一个滚动条
//mui.plusReady(function () {
//	plus.webview.currentWebview().setStyle({
//		scrollIndicator: 'none'
//	});
//});
//document.addEventListener('touchstart', function(event) {
//	// 判断默认行为是否可以被禁用
//	if (event.cancelable) {
//		// 判断默认行为是否已经被禁用
//		if (!event.defaultPrevented) {
//			event.preventDefault();
//		}
//	}
//}, false);

//状态栏透明
window.addEventListener('scroll', function(event){
	var offsetTop = event.detail.y;
	if(offsetTop<-179){
		$('#header').css('background','rgb(255,255,255)');
		$('.xiaoxi').css({'background':'url("../img/news-h.png")','background-size':'cover'});
		$('.zhuce').css({'background':'url("../img/erweima-h.png")','background-size':'cover'});
		$('#present').css('color','#7c7c7a');
		$('#present img').attr('src','../img/location-h.png');
		$('.index-input').css({'color':'#a29f9f','background':'rgba(224, 220, 216,.65) url(../img/search-icon.png) no-repeat center center','background-position-x':'34%','background-size':'20px 20px'});
		$('.more-area').css({'background':'url("../img/more-area-h.png")','background-size':'cover'})
	}else{
		if(-1<offsetTop<-178){
			$('#header').css('background','rgba(255,255,255,.7)');
		}else{
			$('#header').css('background','-webkit-linear-gradient(top, rgba(0, 0, 0, 0.35) 30%, rgba(0, 0, 0, 0))');
		}
		$('.xiaoxi').css({'background':'url("../img/xiaoxi.png")','background-size':'cover'});
		$('.zhuce').css({'background':'url("../img/erweima.png")','background-size':'cover'});
		$('#present').css('color','#fff');
		$('#present img').attr('src','../img/location.png');
		$('.index-input').css({'color':'#dcdcdc','background':'#fff url(../img/index_search_icon.png) no-repeat center center','background-size':'20px 20px','background-position-x':'34%'});
		$('.more-area').css({'background':'url("../img/more-area-icon.png")','background-size':'cover'})
	}
	if(offsetTop<-600){
		$('#header').hide();
		$('#newSHopfixed').show();
		$('#newShop').hide();
		$('#goTop').show();
	}else{
		$('#header').show();
		$('#newSHopfixed').hide();
		$('#newShop').show();
		$('#goTop').hide();
	}
	//回到顶部
	var goTop = document.getElementById('goTop');
	goTop.addEventListener('tap',function(){
		//mui('.mui-scroll-wrapper').scroll().scrollTo(0,0);
		mui('#refreshContainer').pullRefresh().scrollTo(0, 0);//滚动到顶部
		//$('body,html').animate({scrollTop:0},1000);
	})
}, false);

//地图定位
var lng;
var lat;
var locationCity = getItem('locationCity');
var locationCityId = getItem('locationCityId');
var xianId;
function load(){
	if(locationCityId==""||locationCityId==undefined||locationCityId==null){
		xianId='';
		if(locationCity==""||locationCity==undefined||locationCity==null){
			//getLocation();
			setCityItem('locationCity','总部');
		}else{
			$('#locationcity').html(locationCity);
			city = locationCity;
		}
	}else{
		$('#locationcity').html(getItem('locationCity'));
		city = locationCity;
		xianId = locationCityId;
	}
	doHotShop();//加载热门商家
	doNewShop();//加载最新商家
}
load();
function getLocation()
{
	var geolocation = new BMap.Geolocation();

	geolocation.getCurrentPosition(function(r){

		if(this.getStatus() == BMAP_STATUS_SUCCESS){
			lng = r.point.lng;
			lat = r.point.lat;
			$.ajax({
				url: 'https://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location='+lat+','+lng+"&output="+'json',
				data: {
					ak:'WfpHtWKGNVuic7WuI4VpiFueP4KNi1gv',
				},
				dataType: 'jsonp',
				success: function(data) {
					if(data.result.addressComponent.city!=""){
						$('#locationcity').html(data.result.addressComponent.city);
						setCityItem('locationCity',data.result.addressComponent.city);
						city = data.result.addressComponent.city;
						$.ajax({
							url:'/user/updateAddressHistory.json',
							dataType:'json',
							data:{
								city:city,
								token:getItem('token'),
							},
							type:'post',
							success:function(data){

							}
						})
					}else{
						$('#locationcity').html('郑州');
						city = '郑州市';
					}
				},
				error: function() {
					$('#locationcity').html('郑州');
					setCityItem('locationCity','郑州市');
					city = '郑州市';
				}
			})

		}
		else {
			mui.toast('failed'+this.getStatus());

		}
	})
}

//新闻滚动
$(function(){
	$.ajax({
		url:'/InformsC/getSixInforms.json',
		dataType:'json',
		data:{

		},
		type:'post',
		success:function(data){
			if(data.code==1){
				var data = data.datas;
				for(var i=0;i<data.length;i++){
					$('<li id="'+data[i].id+'"><img style="width: 24px;float: left;vertical-align: middle;margin-top: 4px;margin-right: 6px;" src="../img/notice-icon.png" alt="通知">'+data[i].title+'</li>').appendTo($('.scroll-box ul'))
				}
			}
		}
	})
	var $uList = $(".scroll-box ul");
	var timer = null;
    //清空定时器
	$uList.hover(function() {
			clearInterval(timer);
		},
		function() { //离开启动定时器
			timer = setInterval(function() {
					scrollList($uList);
				},
				3000);
		}).trigger("mouseleave"); //自动触发触摸事件
    //滚动动画
	function scrollList(obj) {
		//获得当前<li>的高度
		var scrollHeight = $("ul li:first").height();
		//滚动出一个<li>的高度
		$uList.stop().animate({
				marginTop: -scrollHeight
			},
			600,
			function() {
				//动画结束后，将当前<ul>marginTop置为初始值0状态，再将第一个<li>拼接到末尾。
				$uList.css({
					marginTop: 0
				}).find("li:first").appendTo($uList);
			});
	}
})

//新闻点击
mui('body').on('tap','.scroll-box ul li',function(){
	var newsId = $(this).attr('id');
	window.location.href="news.html";
})

//获取20条分类数据
$(function(){
	$.ajax({
		url:'/categoryC/getCategory.json',
		dataType:'json',
		data:{

		},
		type:'post',
		success:function(data){
			if(data.code==1){
				$('#sortBox1').empty();
				$('#sortBox2').empty();
				var data =data.datas;
				for(var i=0;i<=9;i++){
				$('<a id="'+data[i].ID+'" name="'+data[i].Name+'"><div class="sort"><img src="'+data[i].Img+'"/>'+data[i].Name+'</div></a>').appendTo($('#sortBox1'))
				}
				//for(var a=10;a<=19;a++){
				//$('<a id="'+data[a].ID+'" name="'+data[a].Name+'"><div class="sort"><img src="'+data[a].Img+'"/>'+data[a].Name+'</div></a>').appendTo($('#sortBox2'))
				//}
			}
		}
	})
})

//获取是否有未读消息
$(function(){
	$.ajax({
		url:'/messagesC/countNotReadMessages.json',
		dataType:'json',
		data:{
			token:getItem('token'),
		},
		type:'post',
		success:function(data){
			if(data.code==1){
				var data = data.datas;
				if(data.count==0){
					$('#ifRead').hide();
				}else{
					$('#ifRead').show();
				}
			}
		}
	})
})

//首页轮播图
$(function(){
	$.ajax({
		url:'/bannerC/sixBanner.json',
		dataType:'json',
		success:function(data){
			for(var i=0;i<data.datas.length;i++){
				$('<div class="swiper-slide">'+
					'<a class="banner" href="'+data.datas[i].url+'">'+
					'<img src="'+data.datas[i].img+'">'+
					'</a></div>').appendTo($('#banner'));
			}
			//轮播图
			var mySwiper = new Swiper ('.swiper-container4', {
				loop: true,
				autoplay: 5000,
				pagination: '.swiper-pagination4',
				paginationClickable: true,
			})
			//轮播图跳转
			mui('body').on('tap','.swiper-slide .banner',function(){
				var href = $(this).attr('href');
				window.location.href=href;
			})
		}
	})
})

//获取今日叮当值
$(function(){
	var token = getItem('token');
	if(token==""||token==undefined||token==null){

	}else{
		$.ajax({
			url:'/user/getUserIntegral.json',
			dataType:'json',
			data:{
				token:token,
			},
			type:'post',
			success:function(data){
				if(data.code==1&&data.datas.integral>0){
					var bodyWidth = $('body').outerWidth();
					//var getWidth = $('#get').width()/100*bodyWidth;
					var getWidth = ($('#get').width()/100)*($('.red-box').width()/100*bodyWidth);
					$('#get').css('height',getWidth);
					$('#get span').css('line-height',getWidth+'px');
					$('#big').show();
					var money = data.datas.integral;
					var oChai = document.getElementById("get");

					oChai.onclick = function (){
						oChai.setAttribute("class", "rotate");
						setTimeout(function(){
							window.location.href="hongbao_detail.html?money="+money;
						},1200)
					}
				}

			}
		})

	}
})

//首页漂浮消息
function doOrderMessage(){
	var token = getItem('token');
	if(token==""||token==undefined||token==null){

	}else{
		$.ajax({
			url:'/messagesC/showRedisMessage.json',
			dataType:'json',
			data:{
				token:token,
			},
			type:'post',
			success:function(data){
				if(data.code==1&&data.datas.ifShow){
					var url = data.datas.url;
					var urlLine;
					if(url==""){
						urlLine = '../img/logo_h.jpg'
					}else{
						urlLine = url;
					}
					$('.float-box').html('<img src="'+urlLine+'" alt="img"><div class="float-text-box">'+data.datas.message+'<small>'+data.datas.value+'</small>'+data.datas.type+'</div>');
					var floatHeight = $('.float-box').height();
					if(floatHeight>35){
						$('.float-box').css({'line-height':'23px','padding-top':'1px'})
						$('.float-box img').css({'margin-top':'4px'});
						$('.float-text-box').css({'width':'85%','word-break':'break-all'});
					}else{
						$('.float-box').css({'line-height':'33px','padding-top':'0px'})
						$('.float-box img').css({'margin-top':'0px'});
						$('.float-text-box').css({'width':'auto','word-break':'normal'});
					}
					$('.float-box').show();
					$('.float-box').animate({
						top:12+'%',left:10,
					},3000)

					setTimeout(function () {
						$(".float-box").fadeOut();
						$(".float-box").fadeOut("slow");
						$(".float-box").fadeOut(1000);
						$(".float-box").animate({top : 0, left : 10}, 50)
					}, 4000);
				}else{
					$('.float-box').hide(500);
				}
			}
		})
	}
}

doOrderMessage();

var a = setInterval(doOrderMessage,5000);

//新人红包
$('#draw').click(function () {
    $('#draw').hide();
	$.ajax({
		url:'/user/updateRegisterRedPacket.json',
		dataType:'json',
		data:{
			token:getItem('token'),
		},
		type:'post',
		success:function (data) {
			if(data.code==0){
				mui.toast(data.msg);
				return;
			}
			if(data.code==1){
				$('#money').html(redPacket);
				$('#money').show();
				$('#certain').show();
                $('#packet_money').attr('src','../img/packet_money.jpg');
                window.location.href="hongbao.html?money="+redPacket;
			}
        }
	})
})

$('#certain').click(function () {
    $('.register_packet').hide();
})

$('.close_packet').click(function () {
    $('.register_packet').hide();
    $('.close_packet').hide();
})
var redPacket;
$(function () {
    var token = getItem('token');
    if(token==""||token==undefined||token==null){

    }else{
        $.ajax({
            url:'/user/getRegisterRedPacket.json',
            dataType:'json',
            data:{
                token:getItem('token'),
            },
            success:function (data) {
                if(data.code==1&&data.datas.redPacket>0){
                    redPacket = data.datas.redPacket;
                    $('#draw').show();
                    $('.register_packet').show();
                }
            }
        })
	}
})

$(function () {
	//判断是否为大转盘分享链接
	$.ajax({
		url:'/activityC/isOpenSlyderAdventures.json',
		dataType:'json',
		data:{},
		type:'post',
		success:function (data) {
			if(data.code==1){
				if(data.isOpen){
                    $(".small_lottery").show();
                    var ifLottery = GetQueryString('isdzp');
                    if(ifLottery){
                        $('.big_lottery').show();
                        setItem('isdzp','true');
                    }
                    $('#lottery').click(function () {
                        $('.big_lottery').hide();
                    })
                    $('.go_pump').click(function () {
                        window.location.href="login.html?userId=";
                    })
				}
			}
        }
	})

	//判断是否有userId
	var userId = GetQueryString('userId');
	if(userId==""||userId==undefined||userId==null){

	}else{
		setItem('userId',userId);
	}
})

//小转盘悬浮
$(".small_lottery").click(function(){
    window.location.href="lottery.html";
});
window.addEventListener("swipeup",function(){
    $(".small_lottery img").attr('src','../img/small_lottery.png')
    $(".small_lottery").animate({right:"-77px"});
});
window.addEventListener("swipedown",function(){
    $(".small_lottery img").attr('src','../img/small_lottery2.png')
    $(".small_lottery").animate({right:"-37px"});
});









